package com.hut.oa.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hut.oa.common.WebSocketServer;
import com.hut.oa.model.bean.Announce;
import com.hut.oa.model.bean.AnnounceUser;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.announce.AnnounceDao;
import com.hut.oa.model.dao.announce.AnnounceUserDao;
import com.hut.oa.model.dao.user.UserDao;

@Service
@Transactional(readOnly=true)
public class AnnounceService {
	@Autowired
	AnnounceDao ad;
	
	@Autowired
	AnnounceUserDao aud;
	
	@Autowired
	UserDao ud;

	/**
	 * 保存通知
	 * @param announce
	 */
	@Transactional
	public void saveAnnounce(Announce announce,String message){
		List<AnnounceUser> announceUsers=announce.getAnnounceUsers();
		if(announceUsers!=null){
			for (AnnounceUser announceUser : announceUsers) {
				announceUser.setAnnounce(announce);
			}
			announce.setAnnounceUsers(announceUsers);
		}else{
			//发送给所有人
			WebSocketServer.sendAll(message);
		}
		Announce myAnnounce=ad.save(announce);
		//发送给指定人
		List<AnnounceUser> users=myAnnounce.getAnnounceUsers();
		for (AnnounceUser announceUser2 : users) {
			WebSocketServer.sendMessage(message, announceUser2.getUser().getId());
		}
	}
	
	/**
	 * 添加 生成的系统通知
	 * @param users
	 * @param status
	 * @param message
	 * @param url
	 * @param objectId
	 * @param user
	 */
	public void insertAnnounce(List<User> users,Integer status,String message,String url,Long objectId,User user){
		List<AnnounceUser> announceUsers=new ArrayList<>();
		Announce announce=new Announce(2, status, message, "<a class='link-address' href='"+url+"?id="+objectId+"'>查看详情</a>", user);
		for (User annUser : users) {
			announceUsers.add(new AnnounceUser(annUser,announce));
		}
		announce.setAnnounceUsers(announceUsers);
		this.saveAnnounce(announce, "收到来自【"+user.getName()+"】的通知");
	}
	
	/**
	 * 修改为已读
	 * @param id
	 */
	@Transactional
	public void updateRead(Long id){
		aud.updateRead(id);
	}
}
